package com.lanou.musicproject.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.android.volley.toolbox.ImageLoader;
import com.lanou.musicproject.R;
import com.lanou.musicproject.activity.RotateInfoActivity;
import com.lanou.musicproject.bean.Rotate;
import com.lanou.musicproject.volley.VolleySingleton;

import java.util.List;

/**
 * Created by 王世美 on 15/10/23.
 * 轮播适配器
 */
public class RecommPagerAdapter extends PagerAdapter {
    // 获取轮播图片(randpic)
    private List<Rotate.PicEntity> data;
    // 上下文
    private Context context;
    // 图片加载器
    private ImageLoader imageLoader;

    // 有参构造方法
    public RecommPagerAdapter(Context c, List<Rotate.PicEntity> data) {
        this.context = c;
        this.data = data;
        imageLoader = VolleySingleton.getInstance(context).getImageLoader();
    }

    //获得行布局个数
    @Override
    public int getCount() {
        return Integer.MAX_VALUE;
    }

    //isViewFromObject方法是用来判断pager的一个view是否和instantiateItem方法返回的object有关联。
    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    //初始化行布局item
    @Override
    public Object instantiateItem(ViewGroup container, final int position) {
        ImageView v = new ImageView(context);
        v.setScaleType(ImageView.ScaleType.FIT_XY);
        String image = data.get(position % data.size()).getRandpic();
        ImageLoader.ImageListener listener = ImageLoader.
                getImageListener(v, R.mipmap.baground,
                        R.mipmap.baground);
        imageLoader.get(image, listener);
        //加入布局
        container.addView(v);
        v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Rotate.PicEntity entity = data.get(position % data.size());
                Intent intent = new Intent(context, RotateInfoActivity.class);
                intent.putExtra("listid", entity.getCode());
                context.startActivity(intent);
            }
        });
        return v;
    }

    //destroyitem在viewpager移除一个item时调用
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);

    }
}
